﻿using System;
using System.IO;
using System.Runtime.InteropServices;

namespace CabConfigProvisioning
{
    internal class FdiGenericCallbacks
    {
        public static IntPtr FileOpen(string sFilePath, int oflag, int pmode)
        {
            Stream stream;
            if(!MemoryCache.Instance.TryGetStream(sFilePath, out stream))
                stream = new FileStream(sFilePath, FileMode.Open, FileAccess.Read);
            GCHandle gch = GCHandle.Alloc(stream);
            return (IntPtr)gch;
        }

        public static int FileClose(IntPtr hFile)
        {
            var stream = FxiHelpers.StreamFromHandle(hFile);
            stream.Close();
            ((GCHandle)(hFile)).Free();
            return 0;
        }

        public static int FileRead(IntPtr hFile, byte[] buf, int nSize)
        {
            var stream = FxiHelpers.StreamFromHandle(hFile);
            return stream.Read(buf, 0, nSize);
        }

        public static int FileWrite(IntPtr hFile, byte[] buf, int nSize)
        {
            var stream = FxiHelpers.StreamFromHandle(hFile);
            stream.Write(buf, 0, nSize);
            return nSize;
        }

        public static int FileSeek(IntPtr hFile, int nOfs, int nDirection)
        {
            var stream = FxiHelpers.StreamFromHandle(hFile);
            return (int)stream.Seek(nOfs, (SeekOrigin)nDirection);
        }

        public static IntPtr MemAlloc(int cb)
        {
            return Marshal.AllocHGlobal(cb);
        }

        public static void MemFree(IntPtr mem)
        {
            Marshal.FreeHGlobal(mem);
        }

    }
}
